"""
加密工具
"""

import hmac
import hashlib
from base64 import b64encode
import rsa

__all__ = [
	'API', 'UA', 'SUFFIX_PARAM', 
	'encrypt', 'b64tohex', 'md5', 'calculate_md5_sign'
	'rsa_encode', 'calculate_hmac_sign',
]

API = 'https://api.cloud.189.cn'
UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
# UA = 'Mozilla/5.0'
SUFFIX_PARAM = 'clientType=TELEMAC&version=1.0.0&channelId=web_cloud.189.cn'

RSA_KEY = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDY7mpaUysvgQkbp0iIn2ezoUyh
i1zPFn0HCXloLFWT7uoNkqtrphpQ/63LEcPz1VYzmDuDIf3iGxQKzeoHTiVMSmW6
FlhDeqVOG094hFJvZeK4OzA6HVwzwnEW5vIZ7d+u61RV1bsFxmB68+8JXs3ycGcE
4anY+YzZJcyOcEGKVQIDAQAB
-----END PUBLIC KEY-----
"""
b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
BI_RM = list("0123456789abcdefghijklmnopqrstuvwxyz")


def encrypt(password: str) -> str:
	return b64encode(
		rsa.encrypt(
			(password).encode('utf-8'),
			rsa.PublicKey.load_pkcs1_openssl_pem(RSA_KEY.encode())
		)
	).decode()


def int2char(a):
	return BI_RM[a]


def b64tohex(a):
	d = ""
	e = 0
	for i in range(len(a)):
		if list(a)[i] != "=":
			v = b64map.index(list(a)[i])
			if 0 == e:
				e = 1
				d += int2char(v >> 2)
				c = 3 & v
			elif 1 == e:
				e = 2
				d += int2char(c << 2 | v >> 4)
				c = 15 & v
			elif 2 == e:
				e = 3
				d += int2char(c)
				d += int2char(v >> 2)
				c = 3 & v
			else:
				e = 0
				d += int2char(c << 2 | v >> 4)
				d += int2char(15 & v)
	if e == 1:
		d += int2char(c << 2)
	return d


def md5(s):
	hl = hashlib.md5()
	hl.update(s.encode(encoding='utf-8'))
	return hl.hexdigest()


def calculate_md5_sign(params):
	return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest()


def rsa_encode(j_rsakey, string):
	rsa_key = f"-----BEGIN PUBLIC KEY-----\n{j_rsakey}\n-----END PUBLIC KEY-----"
	pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode())
	result = b64tohex((b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode())
	return result


def calculate_hmac_sign(secret_key, session_key, operate, url, date):
	request_uri = url.split("?")[0].replace(f"{API}", "")
	plain = f'SessionKey={session_key}&Operate={operate}&RequestURI={request_uri}&Date={date}'
	return hmac.new(secret_key.encode(), plain.encode(), hashlib.sha1).hexdigest().upper()
